<template>
  <div class="seckillall">
    <div class="head">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输角色名"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="菜单" prop="roleId">
                    <el-select v-model="queryParams.menuId" placeholder="请选择菜单" filterable>
                        <el-option v-for="item in menus" :label="item.menuName" :key="item.menuId"
                            :value="item.menuId"></el-option>
                    </el-select>
                </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="searchBtn()"
            >搜索</el-button
          >
          <el-button size="default" @click="resetBtn">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="middle">
        <div class="add" style="margin-left: 20px">
          <div class="button">
            <el-button type="primary" :icon="Plus" @click="handleAdd()" plain
              >新增</el-button
            >
          </div>
        </div>
        <div class="add">
          <div class="button">
            <el-button
              type="success"
              :icon="Edit"
              @click="handleEdit()"
              :disabled="single"
              plain
              >修改</el-button
            >
          </div>
        </div>
        <div class="add">
          <div class="button">
            <el-button
              type="danger"
              :icon="Delete"
              @click="handleDelete()"
              :disabled="multiple"
              plain
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
      <div class="end">
        <el-table
          :data="tableData"
          row-key="roleId"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" />
          <el-table-column label="序号" prop="index">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column property="roleName" label="角色名" />
          <el-table-column property="menus" label="菜单" />
          <el-table-column property="description" label="描述" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)"
              v-if="scope.row.roleId !== 1">
                修改
              </el-button>

              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
                v-if="scope.row.roleId !== 1"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-left: 600px">
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>

      <el-dialog v-model="dialogVisible" :modal="true" width="800px">
        <el-form :model="formData" :rules="rules" ref="categoryForm">
          <el-row>
            <el-col :span="16">
              <el-form-item
                label="角色名"
                label-width="120px"
                prop="roleName"
              >
                <el-input
                  v-model="formData.roleName"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            
          </el-row>
          

          <el-row>
            <el-col :span="22">
              <el-form-item
                label="菜单"
                label-width="120px"
              >
                <el-transfer v-model="value" :data="data" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="22">
              <el-form-item
                label="课程备注"
                label-width="120px"
                prop="description"
              >
                <el-input
                  v-model="formData.description"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCanle">取消</el-button>
            <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="deleteDialog" title="Tips" width="500">
        <span>确认要删除吗？</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="deleteDialog = false">取消</el-button>
            <el-button type="primary" @click="deleteConfirm"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Calendar, Search, Edit, Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  selectRoleMenu,
    selectAllMenu,
  getRoleMenu,
  addRoleMenu,
    getRole,
    addRole,
    deleteRole
} from "@/api/user";

//选择框
// const selectable = ref();
const categoryForm = ref(null);
const single = ref(true);
const multiple = ref(true);
const total = ref(10);
const dialogVisible = ref(false);
const selected = ref("add");
//是否禁用表单
const disabled = ref(false);
const selectRow = ref([]);
const deleteDialog = ref(false);
const deleteRow = ref([]);
const teacherList = ref([]);
const categoryList = ref([]);
const menus = ref([]);

/**
 * @typedef {{
 * menuId: number
 * menuName: string
 * }} MenuItem
 * /
 * @type {MenuItem[]} */

const data = ref(/* @type {MenuItem[]} */ ([])) 
const value = ref(/* @type {number[]} */ ([]))


onMounted(async () => {
  // await getTeacherList();
  await getAllMenus();
  await getRoleList();
});
//查询参数
const queryParams = ref({
  // courseId: '',
  roleName: '',
  // courseStatus: '',
  pageNum: 1,
  pageSize: 8,
  // categoryId: '',
  // teacherId: '',
});

const addMenuList = ref({
  roleId: "",
  menuIds: String
});
// 表单参数
var formData = ref({
  roleId: "",
  menuId: "",
  menuName: "",
  menus: "",
  description: "",
});
//表格参数
const tableData = ref([]);

const rules = {
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  description: [{ required: true, message: "", trigger: "blur" }],
};



// 修改
function handleEdit(row) {
  if (row == null) {
    row = selectRow.value[0];
  }
  disabled.value = true;
  selected.value = "edit";
  const data = {
    roleId: row.roleId,
  };
  getRole(data).then((res) => {
    formData.value = res.data.getRole[0];
  });
  getRoleMenu(data).then((res) => {
    let menus = res.data.getRoleMenu;
    const menuIds = menus.map(item => item.menuId);
    value.value = menuIds;
 
  dialogVisible.value = true;
  });
}
// 删除
function handleDelete(row) {
  if (row == null) {
    row = selectRow.value.map((item) => {
      return item.roleId;
    });
  } else {
    row = [row.roleId];
  }
  deleteRow.value = row;
  deleteDialog.value = true;
}
// 删除确定
function deleteConfirm() {
    console.log(deleteRow.value,9999999999999);
  deleteRole(deleteRow.value).then((res) => {
    if (res.code === 500) {
      ElMessage.error(res.message);
    } else {
      ElMessage.success("删除成功");
    }
    getRoleList();
  });
  deleteDialog.value = false;
}

//新增
function handleAdd() {
  dialogVisible.value = true;
  selected.value = "add";
}
//每页条数变换
function handleSizeChange(val) {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;
  getRoleList();
}
//每码变换
function handleCurrentChange(val) {
  queryParams.value.pageNum = val;
  getRoleList();
}

//关闭dialog
function handleCanle() {
  dialogVisible.value = false;
  // 重置表单字段
  categoryForm.value.resetFields();

  // 清除表单验证
  categoryForm.value.clearValidate();
}

// 选中某一列
function handleSelectionChange(selected) {
  // console.log(selected, selected.length);
  single.value = selected.length != 1;
  multiple.value = selected.length == 0;
  selectRow.value = selected;
}

function handleConfirm() {
  // 验证表单 xxx
  categoryForm.value.validate((valid) => {
    // 重置表单字段
    // categoryForm.value.resetFields();
    if (valid) {
      // 表单验证通过，执行提交操作
      if (selected.value === "add") {
        const addData = {
          roleId: formData.value.roleId,
          menuIds: value.value,
          roleName: formData.value.roleName,
          description: formData.value.description
        };
        
        addRole(addData).then((res) => {
          console.log(res);
          if (res.code === 500) {
            ElMessage.error(res.message);
          } else {
            ElMessage.success("新增成功");
          }
          getRoleList();
          dialogVisible.value = false;
          value.value = [];
  categoryForm.value.resetFields();
  // 清除表单验证
  categoryForm.value.clearValidate();
        });
      } else {
        const addData = {
          roleId: formData.value.roleId,
          menuIds: value.value 
        };
        addRoleMenu(addData).then((res) => {
          // if (res.code === 500) {
          //   ElMessage.error(res.message);
          // } else {
            ElMessage.success("修改成功");
          // }
          getRoleList();
          dialogVisible.value = false;
        });
      }
    } else {
      // 表单验证失败，显示错误信息
      ElMessage.warning("请填写完整");
    }
  });
  
}

function searchBtn() {
  queryParams.value.pageNum = 1;
  getRoleList();
}

function resetBtn() {
  queryParams.value = {
    roleName: "",
    pageNum: 1,
    pageSize: queryParams.value.pageSize,
  };
  getRoleList();
}

async function getRoleList() {
  try {
    const res = await selectRoleMenu(queryParams.value);
    total.value = res.data.roleMenu.total;
    tableData.value = res.data.roleMenu.records;
    const ress = await selectAllMenu();
    menus.value = ress.data.menus;
 
  } catch (error) {
    console.log(error);
  }
}
async function getAllMenus() {
  try {
    const res = await selectAllMenu(data.value);
    data.value = res.data.menus.map(item => ({
      key: item.menuId,
      label: item.menuName
    }));
  } catch (error) {
    console.error("获取菜单失败:", error);
  }
}

</script>

<style scoped>
.seckillall {
  height: 100%;
  width: calc(100% - 50px);
  /* background-color: pink; */
  float: left;
}

.head {
  margin-top: 20px;
  margin-left: 20px;
  width: calc(100% - 50px);
}

.middle {
  width: 100%;
  height: 8vh;
  /* background-color: antiquewhite; */
  margin-bottom: 20px;
}

.add {
  margin-top: 15px;
  margin-left: 45px;
  width: 5%;
  height: 50%;
  float: left;
}

.end {
  float: left;
  width: calc(100% - 50px);
}
</style>